package cn.lingyangwl.agile.model.module.auth;

import cn.lingyangwl.framework.tool.core.Base64Utils;
import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 用户的资源权限信息
 * @author shenguangyang
 */
@Slf4j
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
public class UserAuthority implements Serializable {

    /**
     * 资源操作标识符
     */
    private Set<String> actions = Collections.emptySet();

    /**
     * 资源地址
     */
    private Set<String> resourceUrls = Collections.emptySet();

    /**
     * 数据规则列表
     */
    private List<UserDataRule> dataRules = Collections.emptyList();

    public String encodeToString() {
        return Base64Utils.encode(JSON.toJSONString(this));
    }

    public static UserAuthority decode(String encodedStr) {
        try {
            if (StringUtils.isEmpty(encodedStr)) {
                return null;
            }
            return JSON.parseObject(Base64Utils.decode(encodedStr), UserAuthority.class);
        } catch (IOException e) {
            log.error("error: {}, encodedStr: {}", e.getMessage(), encodedStr);
            throw new BizException("解析用户信息失败");
        }
    }


}
